import {
	fileApi
} from '@/pages-menus/common/api/file/index.js'

// 构建上传成功的文件对象
const buildFormattedFile = (fileObj, response) => ({
	uid: fileObj.uid,
	name: fileObj.name,
	status: 'done',
	extname: 'text',
	url: response?.data?.url || response?.data?.path,
	res: response?.data,
})

// 上传文件自定义的方法
export const myUpload = (requestObj, options) => {
	const opt = {
		apiFunc: fileApi.upload,
		apiData: {},
		...options,
	}
	return new Promise((resolve, reject) => {
		// 检查文件对象是否有效
		if (!requestObj || !requestObj) {
			return reject(new Error('缺少有效的文件对象'))
		}

		const fileObj = requestObj

		// 小程序文件转base64
		uni.getFileSystemManager().readFile({
			filePath: fileObj.tempFilePath,
			encoding: 'base64',
			success: async res => {
				const base64Data = res.data

				const myData = typeof opt.apiData === 'function' ? opt.apiData({
					...fileObj,
					base64Data
				}) : opt.apiData
				// 构建请求数据
				const uploadData = {
					fileName: fileObj.name, // 文件名
					file: base64Data, // 去掉前缀的 Base64 数据
					...myData,
				}

				// 调用上传函数
				const response = await opt.apiFunc(uploadData)
				// 检查上传是否成功
				if (response.data && response.code === 200) {
					const formattedFile = buildFormattedFile(fileObj, response)
					fileObj.onSuccess(response)
					resolve(formattedFile)
				} else {
					const errorMessage = response?.data?.message || response?.data?.msg ||
						response
						?.msg || '上传失败'
					uni.showToast({
						title: `${errorMessage}`,
						icon: 'error',
						duration: 2000
					});
					reject(new Error(errorMessage))
				}
			}
		})
	})
}